package com.tywj.navigation.popupwindow

import android.annotation.SuppressLint
import android.app.Activity
import android.content.Context
import android.content.Intent
import android.graphics.Rect
import android.graphics.drawable.ColorDrawable
import android.net.Uri
import android.os.Build
import android.util.AttributeSet
import android.view.Gravity
import android.view.LayoutInflater
import android.view.View
import android.widget.LinearLayout
import android.widget.PopupWindow
import android.widget.TextView
import com.amap.api.maps.model.LatLng
import com.tywj.lib.core.common.extension.onClick
import com.tywj.lib.core.common.util.ResourcesUtil
import com.tywj.lib.core.common.util.ToastUtil.shortToast
import com.tywj.navigation.R
import com.tywj.panda.customer.common.tool.NavigationTool.isInstalled

/**
 * 去导航
 */
class NavigationPopupWindow : PopupWindow {
    private var context: Activity? = null

    //kotlin中注意命名冲突，不能用contentView 会和getContentView冲突，用view代替
    private var view: View? = null
    private var start: LatLng? = null
    private var app: TextView? = null
    private var gd: TextView? = null
    private var bd: TextView? = null
    private var tx: TextView? = null

    private var tvCancel: TextView? = null

    //App内导航监听
    private var listener: (() -> Unit?)? = null

    constructor(context: Context?, start: LatLng?) : super(context) {
        this.context = context as Activity?
        this.start = start
        initPopupWindow()
    }

    constructor(context: Context?, attrs: AttributeSet?) : super(context, attrs) {}
    constructor(
        context: Context?,
        attrs: AttributeSet?,
        defStyleAttr: Int
    ) : super(context, attrs, defStyleAttr) {
    }

    @SuppressLint("InflateParams")
    private fun initPopupWindow() {
        val inflater = context?.getSystemService(Context.LAYOUT_INFLATER_SERVICE) as LayoutInflater
        view = inflater.inflate(R.layout.navigation_popuwindow_map_selected, null)

        contentView = view

        this.width = LinearLayout.LayoutParams.MATCH_PARENT
        this.height = LinearLayout.LayoutParams.WRAP_CONTENT
        // 设置SelectPicPopupWindow弹出窗体可点击
        this.isFocusable = true
        this.isOutsideTouchable = true
        // 刷新状态
        this.update()
        val dw = ColorDrawable(ResourcesUtil.getColor(R.color.common_gray_D5))
        setBackgroundDrawable(dw)

        this.animationStyle = android.R.style.Animation_Dialog

        app = view?.findViewById(R.id.tv_app)
        gd = view?.findViewById(R.id.to_gd)
        bd = view?.findViewById(R.id.to_bd)
        tx = view?.findViewById(R.id.to_tx)

        tvCancel = view?.findViewById(R.id.tvCancel)

        app?.onClick {
            listener?.invoke()
            dismiss()
        }

        gd?.setOnClickListener(View.OnClickListener {
            if (!isInstalled("com.autonavi.minimap", context!!)) {
                shortToast("检测到您未安装高德地图")
                return@OnClickListener
            }
            val stringBuffer =
                StringBuffer("amapuri://route/plan/?sourceApplication=").append("胖哒直通车")
            stringBuffer.append("&dlat=").append(start!!.latitude)
                .append("&dlon=").append(start!!.longitude)
                .append("&dev=").append(0)
                .append("&t=").append(2)
            val intent =
                Intent("android.intent.action.VIEW", Uri.parse(stringBuffer.toString()))
            intent.setPackage("com.autonavi.minimap")
            context?.startActivity(intent)
        })

        bd?.setOnClickListener(View.OnClickListener {
            if (!isInstalled("com.baidu.baidumap", context!!)) {
                shortToast("检测到您未安装百度地图")
                return@OnClickListener
            }
            val stringBuffer = StringBuffer("baidumap://map/direction?")
            stringBuffer.append("destination=").append(start!!.latitude)
                .append(",").append(start!!.longitude)
                .append("&coord_type=").append("gcj02")
                .append("&mode=").append("walking")
            val i1 = Intent()
            i1.data = Uri.parse(stringBuffer.toString())
            context?.startActivity(i1)
        })

        tx?.setOnClickListener(View.OnClickListener {
            if (!isInstalled("com.tencent.map", context!!)) {
                shortToast("检测到您未安装腾讯地图")
                return@OnClickListener
            }
            val stringBuffer = StringBuffer("qqmap://map/routeplan?")
            stringBuffer.append("type=").append("walk")
                .append("&tocoord=").append(start!!.latitude).append(",").append(start!!.longitude)
                .append("&referer=").append("LQDBZ-GOEKP-I7IDR-LZ3V6-6YRCH-2NF2Z")
            val intent = Intent()
            intent.data = Uri.parse(stringBuffer.toString())
            context?.startActivity(intent)
        })

        tvCancel?.onClick {
            dismiss()
        }
    }

    fun showAtDropDownCenter(parent: View) {
        if (parent.visibility == View.GONE) {
            showAtLocation(parent, Gravity.BOTTOM, 0, 0)
        } else {
            showAtLocation(parent, Gravity.BOTTOM, 0, 0)
        }
    }

    override fun showAsDropDown(anchor: View) {
        if (Build.VERSION.SDK_INT >= 24) {
            val visibleFrame = Rect()
            anchor.getGlobalVisibleRect(visibleFrame)
            val height = anchor.resources.displayMetrics.heightPixels - visibleFrame.bottom
            setHeight(height)
        }
        super.showAsDropDown(anchor)
    }

    fun goHereListener(listener: () -> Unit) {
        this.listener = listener
    }
}